package com.tm.chargecar.handler;

import com.tm.chargecar.exception.BizException;
import com.tm.chargecar.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import static com.tm.chargecar.enums.ResultEnum.ADD_ERROR;


@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(BizException.class)
    public Result bizException(BizException exception){
        log.error("自定义异常全局捕获,错误码:{},msg={}",exception.getCode(),exception.getMsg());
        exception.printStackTrace();
        return Result.ERROR(exception.getCode(),exception.getMsg());
    }


    @ExceptionHandler(Exception.class)
    public Result exception(Exception exception){
    log.error(exception.getCause().getMessage());
        exception.printStackTrace();
        return Result.ERROR();
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result MethodArgumentNotValidException(MethodArgumentNotValidException exception){
       log.error(exception.getMessage());
        Integer code = ADD_ERROR.getCode();
        String defaultMessage = exception.getBindingResult().getFieldError().getDefaultMessage();
        return Result.ERROR(code,defaultMessage);
    }

}
